/*
 * SunSpotApplication.java
 *
 * Created on Apr 12, 2011 8:56:47 AM;
 */

package org.sunspotworld;

import com.sun.spot.core.resources.transducers.ILightSensor;
import com.sun.spot.core.resources.transducers.ISwitch;
import com.sun.spot.core.util.Utils;
import com.sun.spot.edemo.EDemoBoard;
import com.sun.spot.edemo.peripheral.EDemoSerial;
import com.sun.spot.espot.service.BootloaderListenerService;
import java.io.DataOutputStream;
import java.io.IOException;

import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

/**
 * The startApp method of this class is called by the VM to start the
 * application.
 * 
 * The manifest specifies this class as MIDlet-1, which means it will
 * be selected for execution.
 */
public class SunSpotApplication extends MIDlet {

    private EDemoSerial serial = new EDemoSerial();
    private DataOutputStream out;
    private ISwitch[] sw;
    private ILightSensor light;
    private int lightIntensity; 

    protected void startApp() throws MIDletStateChangeException {
        BootloaderListenerService.getInstance().start();   // monitor the USB (if connected) and recognize commands from host

        sw = EDemoBoard.getInstance().getSwitches();
        light = EDemoBoard.getInstance().getLightSensor();

        try {
            //These are the default USART params on the WiFly
            serial.setUSARTParams(9600, 8, "none", 1);
            out = serial.openDataOutputStream();
        } catch(IOException e) {

        }

        //Controlled loop to get data and send it
        while(sw[0].isOpen() || sw[1].isOpen()) {

            try {
                lightIntensity = light.getValue();
                out.writeInt(lightIntensity); //4 bytes
                out.flush(); //Total Bytes sent 4
                Utils.sleep(1000);
            } catch(IOException e) {
                
            }

        }

        notifyDestroyed();                      // cause the MIDlet to exit
    }

    protected void pauseApp() {
        // This is not currently called by the Squawk VM
    }

    /**
     * Called if the MIDlet is terminated by the system.
     * It is not called if MIDlet.notifyDestroyed() was called.
     *
     * @param unconditional If true the MIDlet must cleanup and release all resources.
     */
    protected void destroyApp(boolean unconditional) throws MIDletStateChangeException {
    }
}
